package com.zhang.family_doctor.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhang.family_doctor.dto.PaymentDto;
import com.zhang.family_doctor.dto.SignUpDetailsDto;
import com.zhang.family_doctor.dto.SignUpDto;
import com.zhang.family_doctor.entity.Packages;
import com.zhang.family_doctor.entity.R;
import com.zhang.family_doctor.entity.SignUp;
import com.zhang.family_doctor.mapper.PackagesMapper;
import com.zhang.family_doctor.mapper.SignUpMapper;
import com.zhang.family_doctor.service.SignUpService;
import com.zhang.family_doctor.utils.CommonUtils;
import com.zhang.family_doctor.utils.HttpClientUtil2;
import com.zhang.family_doctor.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class signUpServiceImpl implements SignUpService {

    @Autowired
    private SignUpMapper signUpMapper;

    @Autowired
    private PackagesMapper packagesMapper;

    /**
     * 居民提交申请签约
     * @param signUp
     * @param request
     * @return
     */
    @Override
    public R<String> applySigning(SignUp signUp, HttpServletRequest request) {

        //从token中拿到居民id
        String tokenResident = request.getHeader("tokenResident");
        Integer getId = Integer.valueOf(TokenUtils.verifyAndGetId(tokenResident));

        //根据服务包id查询服务包
        Integer packagesId = signUp.getPackagesId();
        Packages packages = packagesMapper.getPackagesById(packagesId);
        //拿到服务包的签约周期
        Integer signingPeriod = packages.getSigningPeriod();

        //生效日期
        Date effectiveDate = signUp.getEffectiveDate();

        //签约周期分为1年、2年、3年
        if (signingPeriod == 1){
            //计算失效日期 一年
            Calendar calendarOne = Calendar.getInstance();
            calendarOne.setTime(effectiveDate);
            calendarOne.add(calendarOne.YEAR, 1);
            effectiveDate = calendarOne.getTime();

        }else if (signingPeriod == 2){
            //计算失效日期 两年
            Calendar calendarTwo = Calendar.getInstance();
            calendarTwo.setTime(effectiveDate);
            calendarTwo.add(calendarTwo.YEAR, 2);
            effectiveDate = calendarTwo.getTime();
        }else if (signingPeriod == 3){
            //计算失效日期 一年
            Calendar calendarThree = Calendar.getInstance();
            calendarThree.setTime(effectiveDate);
            calendarThree.add(calendarThree.YEAR, 3);
            effectiveDate = calendarThree.getTime();
        }

        signUp.setId(CommonUtils.genUUID());
        signUp.setNumber(CommonUtils.genUUID());
        signUp.setResidentId(getId);
        //续约次数默认为0
        signUp.setNumberRenewals(0);
        signUp.setApplicationTime(new Date());
        signUp.setExpiryDate(effectiveDate);
        signUp.setUpdateTime(new Date());
        //默认待审核状态
        signUp.setStatus(1);
        List<SignUp> signUpByResidentId = signUpMapper.getSignUpByResidentId(getId);
        //判断该居民是否有签过约
        if (signUpByResidentId.size() == 0){
            //二次签约
            signUp.setSigningType(1);
            signUpMapper.save(signUp);
            return R.success("申请成功！");
        }
        //首次签约
        signUp.setSigningType(2);
        signUpMapper.save(signUp);
        return R.success("申请成功！");
    }

    /**
     * 审核通过签约申请
     * @param signUp
     * @param request
     * @return
     */
    @Override
    public R<String> doctorAudit(SignUp signUp, HttpServletRequest request) {
        //医生端的token
        String tokenDoctor = request.getHeader("tokenDoctor");
        //后台的token
        String tokenBackstage = request.getHeader("tokenBackstage");

        signUp.setAuditTime(new Date());
        if (tokenDoctor != null){
            String doctorName = TokenUtils.verifyAndGetDoctorName(tokenDoctor);
            signUp.setStatus(3);
            signUp.setReviewed(doctorName);
            signUpMapper.doctorAudit(signUp);

            return R.success("审核通过！");

        }
        if (tokenBackstage != null){
            String getName = TokenUtils.verifyAndGetName(tokenBackstage);
            signUp.setStatus(3);
            signUp.setReviewed(getName);
            signUpMapper.doctorAudit(signUp);

            return R.success("审核通过！");
        }
        return R.buildFailure("审核出错！");
    }

    /**
     * 驳回申请
     * @param signUp
     * @param request
     * @return
     */
    @Override
    public R<String> reject(SignUp signUp, HttpServletRequest request) {
        //医生端的token
        String tokenDoctor = request.getHeader("tokenDoctor");
        //后台的token
        String tokenBackstage = request.getHeader("tokenBackstage");

        signUp.setAuditTime(new Date());
        if (tokenDoctor != null){
            String doctorName = TokenUtils.verifyAndGetDoctorName(tokenDoctor);
            signUp.setStatus(2);
            signUp.setReviewed(doctorName);
            signUpMapper.reject(signUp);
            return R.success("驳回成功！");
        }
        if (tokenBackstage != null){
            String getName = TokenUtils.verifyAndGetName(tokenBackstage);
            signUp.setStatus(2);
            signUp.setReviewed(getName);
            signUpMapper.reject(signUp);
            return R.success("驳回成功！");
        }
        return R.buildFailure("审核出错！");
    }

    /**
     * 续约申请
     * @param signUp
     * @return
     */
    @Override
    public R<String> renewalApplication(SignUp signUp) {

        Integer id = signUp.getId();

        SignUp signUpById = signUpMapper.getSignUpById(id);
        Date effectiveDate = signUpById.getEffectiveDate();
        Date renewalDate = signUpById.getRenewalDate();
        Integer renewalsStatus = signUpById.getRenewalsStatus();
        //给驳回续约申请再次申请
        if (renewalsStatus == 2){
            Integer numberRenewals = signUpById.getNumberRenewals();
            Integer num = numberRenewals + 1;
            //默认为待审核状态
            signUp.setRenewalsStatus(1);
            //续约次数加一
            signUp.setNumberRenewals(num);
            //续约后改为二次续约
            signUp.setSigningType(2);
            signUp.setRenewalsTime(new Date());
            signUpMapper.renewalApplicationAgain(signUp);

            return R.success("重新续约申请成功！");
        }
        //在审核状态或通过状态没生效时则无法再续约
        if (renewalDate.compareTo(effectiveDate) == 0){
            Integer numberRenewals = signUpById.getNumberRenewals();
            Integer num = numberRenewals + 1;

            //默认为待审核状态
            signUp.setRenewalsStatus(1);
            //续约次数加一
            signUp.setNumberRenewals(num);
            //续约后改为二次续约
            signUp.setSigningType(2);
            signUp.setRenewalsTime(new Date());
            signUpMapper.renewalApplication(signUp);

            return R.success("续约申请成功！");
        }
        return R.buildFailure("已经申请过续约还没生效！");

    }

    /**
     * 通过续约申请
     * @param signUp
     * @param request
     * @return
     */
    @Override
    public R<String> renewalApproved(SignUp signUp, HttpServletRequest request) {
        //医生端的token
        String tokenDoctor = request.getHeader("tokenDoctor");
        //后台的token
        String tokenBackstage = request.getHeader("tokenBackstage");

        signUp.setRenewalsAuditTime(new Date());
        if (tokenDoctor != null){
            String doctorName = TokenUtils.verifyAndGetDoctorName(tokenDoctor);
            signUp.setRenewalsStatus(3);
            signUp.setReviewedRenewals(doctorName);
            signUpMapper.renewalApproved(signUp);

            return R.success("审核通过！");

        }
        if (tokenBackstage != null){
            String getName = TokenUtils.verifyAndGetName(tokenBackstage);
            signUp.setRenewalsStatus(3);
            signUp.setReviewedRenewals(getName);
            signUpMapper.renewalApproved(signUp);

            return R.success("审核通过！");
        }
        return R.buildFailure("审核出错！");
    }

    /**
     * 驳回续约申请
     * @param signUp
     * @param request
     * @return
     */
    @Override
    public R<String> rejectRenewalApplication(SignUp signUp, HttpServletRequest request) {
        //医生端的token
        String tokenDoctor = request.getHeader("tokenDoctor");
        //后台的token
        String tokenBackstage = request.getHeader("tokenBackstage");

        signUp.setRenewalsAuditTime(new Date());
        if (tokenDoctor != null){
            String doctorName = TokenUtils.verifyAndGetDoctorName(tokenDoctor);
            signUp.setRenewalsStatus(2);
            signUp.setReviewedRenewals(doctorName);
            signUpMapper.rejectRenewalApplication(signUp);
            return R.success("驳回成功！");
        }
        if (tokenBackstage != null){
            String getName = TokenUtils.verifyAndGetName(tokenBackstage);
            signUp.setRenewalsStatus(2);
            signUp.setReviewedRenewals(getName);
            signUpMapper.rejectRenewalApplication(signUp);
            return R.success("驳回成功！");
        }
        return R.buildFailure("审核出错！");
    }

    /**
     * 调用微信练习中的微信支付接口
     * @return
     * @param paymentDto
     */
    @Override
    public R<String> weChatPayment(PaymentDto paymentDto) {

        //拿到登录验证的token
        String token = HttpClientUtil2.doGet("http://localhost:8084/user/logins?account=34945245&password=123456");
        paymentDto.setToken(token);

        String s1 = JSON.toJSONString(paymentDto);

        String s = HttpClientUtil2.doPost("http://localhost:8084/payment/weChatPayment", s1,paymentDto);//,token
        return R.success(s);
    }

    /**
     * 支付成功的接口
     * @param paymentDto
     * @return
     */
    @Override
    public R<String> paymentSucceeded(PaymentDto paymentDto) {

        SignUp signUp = new SignUp();
        String name = paymentDto.getName();
        Integer signUpId = paymentDto.getSignUpId();
        String s = "微信支付";
        String str = "支付宝支付";

        SignUp signUpById = signUpMapper.getSignUpById(signUpId);
        Integer renewalsStatus = signUpById.getRenewalsStatus();
        Integer status = signUpById.getStatus();
        if (renewalsStatus == 3){
            if (name.equals(s)){

                signUp.setRenewalsStatus(4);
                signUp.setRenewalsPaymentTime(new Date());
                signUp.setRenewalsPaymentMethod(1);
                signUp.setId(signUpId);
                signUpMapper.renewalsPaymentSucceeded(signUp);
                return R.success("支付成功！");
            }
            if (name.equals(str)){

                signUp.setRenewalsStatus(4);
                signUp.setRenewalsPaymentTime(new Date());
                signUp.setRenewalsPaymentMethod(1);
                signUp.setId(signUpId);
                signUpMapper.renewalsPaymentSucceeded(signUp);
                return R.success("支付成功！");
            }
        }
        if (status == 3) {
            if (name.equals(s)) {

                signUp.setStatus(4);
                signUp.setPaymentTime(new Date());
                signUp.setPaymentMethod(1);
                signUp.setId(signUpId);
                signUpMapper.paymentSucceeded(signUp);
                return R.success("支付成功！");
            }
            if (name.equals(str)) {

                signUp.setStatus(4);
                signUp.setPaymentTime(new Date());
                signUp.setPaymentMethod(2);
                signUp.setId(signUpId);
                signUpMapper.paymentSucceeded(signUp);
                return R.success("支付成功！");
            }
        }

        return R.buildFailure("支付失败！");
    }

    @Override
    public R<String> alipayPayment(PaymentDto paymentDto) {

        String token = HttpClientUtil2.doGet("http://localhost:8084/user/logins?account=34945245&password=123456");
        paymentDto.setToken(token);

        String s1 = JSON.toJSONString(paymentDto);
        String s = HttpClientUtil2.doPost("http://localhost:8084/payment/alipayPayment", s1,paymentDto);//,token
        return R.success(s);
    }

    /**
     * 居民端查看签约记录
     * @param request
     * @return
     */
    @Override
    public R<List<SignUp>> getSignUp(HttpServletRequest request) {
        String tokenResident = request.getHeader("tokenResident");
        Integer getId = Integer.valueOf(TokenUtils.verifyAndGetId(tokenResident));

        List<SignUp> signUpByResidentId = signUpMapper.getSignUpByResidentId(getId);

        return R.success(signUpByResidentId);
    }

    /**
     * 居民端查看签约详情
     * @param id
     * @return
     */
    @Override
    public R<SignUpDetailsDto> getSignUpDetails(Integer id) {

        SignUpDetailsDto signUpDetails = signUpMapper.getSignUpDetails(id);

        return R.success(signUpDetails);
    }

    /**
     * 分页查询待处理签约
     * @param signUpDto
     * @return
     */
    @Override
    public R<PageInfo<SignUpDto>> getPending(SignUpDto signUpDto) {
        Integer pageNum = signUpDto.getPageNum();
        Integer pageSize = signUpDto.getPageSize();
        PageHelper.startPage(pageNum,pageSize);

        List<SignUpDto> signUpDtoList = signUpMapper.getPending(signUpDto);

        PageInfo<SignUpDto> signUpDtoPageInfo = new PageInfo<>(signUpDtoList);


        return R.success(signUpDtoPageInfo);
    }


}
